package com.shanzmoo.job.web;

import com.shanzmoo.base.bean.SHttpResponse;
import com.shanzmoo.db.job.entity.ScheduleJobEntity;
import com.shanzmoo.db.job.entity.dto.ScheduleJobSaveDto;
import com.shanzmoo.db.job.entity.vo.ScheduleJobVo;
import com.shanzmoo.job.base.BaseTask;
import com.shanzmoo.job.manager.ScheduleJobManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 调度任务管理
 * @author: Gzhao 2020/12/24
 */
@Slf4j
@Api(tags = "系统-调度任务管理")
@RestController
@RequestMapping("/api/sys/job")
public class ScheduleJobController {

    @Autowired
    private ScheduleJobManager scheduleJobManager;

    @ApiOperation(value = "定时任务列表")
    @GetMapping("/list")
    public SHttpResponse<List<ScheduleJobVo>> list() {
        List<ScheduleJobVo> jobs = scheduleJobManager.allList();
        return SHttpResponse.ok(jobs);
    }

    @ApiOperation(value = "保存(更新)定时任务")
    @PostMapping("/saveOrUpdate")
    public SHttpResponse<Boolean> save(@Valid @RequestBody ScheduleJobSaveDto scheduleJob) {

        ScheduleJobEntity jobEntity = scheduleJob.convert();
        jobEntity.setStatus(false);

        if (null != jobEntity.getJobId() && jobEntity.getJobId() > 0){
            scheduleJobManager.updateJob(jobEntity);

        } else {
            jobEntity.setMethodName(BaseTask.methodName);
            scheduleJobManager.saveJob(jobEntity);
        }
        return SHttpResponse.ok(Boolean.TRUE);
    }

    @ApiOperation(value = "删除定时任务")
    @GetMapping("/delete/{jobId}")
    public SHttpResponse<Boolean> deleteJob(@PathVariable Long jobId) {
        scheduleJobManager.deleteJob(jobId);
        return SHttpResponse.ok(Boolean.TRUE);
    }

    @ResponseBody
    @ApiOperation(value = "立即执行任务")
    @GetMapping("/runNow/{jobId}")
    public SHttpResponse<Boolean> runNow(@PathVariable Long jobId) {
        scheduleJobManager.run(jobId);
        return SHttpResponse.ok();
    }

    @ResponseBody
    @ApiOperation(value = "暂停任务")
    @GetMapping("/pause/{jobId}")
    public SHttpResponse<Boolean> pause(@PathVariable Long jobId) {
        scheduleJobManager.pause(jobId);

        log.info("任务ID{}，执行器暂停", jobId);
        return SHttpResponse.ok();
    }

    @ResponseBody
    @ApiOperation(value = "启动任务")
    @GetMapping("/start/{jobId}")
    public SHttpResponse<Boolean> start(@PathVariable Long jobId) {
        scheduleJobManager.start(jobId);

        log.info("任务ID{}，执行器启动", jobId);
        return SHttpResponse.ok();
    }


}
